import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class SeaMooenController extends GetxController {
  final double seaLevel = Get.height - 180.0;
  final double finalPosition = 300;
  final int starCount = 80;
  late double _moonCenterY;
  get moonCenterY => _moonCenterY;

  late double _wingHeight;
  get wingHeight => _wingHeight;

  late double _waveY;
  get waveY => _waveY;

  late double _waveRadius;
  get waveRadius => _waveRadius;

  late double _birdFlyDistance;
  get birdFlyDistance => _birdFlyDistance;

  late List<Offset> _starPositions;
  get starPositions => _starPositions;
  late List<double> _starSizes;
  get starSizes => _starSizes;
  late List<bool> _blinkIndexes;
  get blinkIndexes => _blinkIndexes;

  late int _waveMoveCount;
  final int waveMoveStep = 20;
  bool moveForward = true;
  bool first = true;

  late Timer _downcountTimer;

  @override
  void onInit() {
    _moonCenterY = seaLevel;
    _waveY = 0;
    _waveMoveCount = 0;
    _waveRadius = 200.0;
    _wingHeight = 10;
    _birdFlyDistance = 0;
    var starmoonCenterY = seaLevel - 20.0;
    _starPositions = List.generate(
      starCount,
      (index) => Offset(
        4.0 + Random().nextInt(Get.width.toInt() - 4),
        starmoonCenterY - Random().nextInt(starmoonCenterY.toInt()),
      ),
    );
    _starSizes =
        List.generate(starCount, (index) => Random().nextInt(10) / 3.0);
    _blinkIndexes = List.generate(
        starCount, (index) => Random().nextInt(starCount) % 3 == 0);
    super.onInit();
  }

  @override
  void onReady() {
    _downcountTimer = Timer.periodic(Duration(milliseconds: 40), repaint);
    super.onReady();
  }

  void repaint(Timer timer) {
    bool needUpdate = false;
    if (_moonCenterY > finalPosition) {
      _moonCenterY -= 1;
      needUpdate = true;
    } else {
      timer.cancel();
    }
    _waveMoveCount++;
    _birdFlyDistance += 0.5;
    int maxStep = first ? waveMoveStep : waveMoveStep * 2;

    if (moveForward) {
      _waveY += 0.5;
      _wingHeight -= 0.3;
    } else {
      _waveY -= 0.5;
      _wingHeight += 0.3;
    }
    if (_waveMoveCount > maxStep) {
      _waveMoveCount = 0;
      first = false;
      moveForward = !moveForward;
    }

    _blinkIndexes = List.generate(
        starCount, (index) => Random().nextInt(starCount) % 2 == 0);

    _waveRadius = 200.0 + _waveY;

    if (needUpdate) {
      update();
    }
  }

  @override
  void onClose() {
    _downcountTimer.cancel();
    super.onClose();
  }
}
